<?php
class Front extends Controller {

    function Front() {
        parent::Controller();
        session_start();
        $this->lang->load("front");
    }

    function index() {
        redirect(base_url().$this->lang->lang().'/front/chooseMunicipality', 'refresh');
    }

    function chooseMunicipality() {
        if(isset($_SESSION['sendData'])){
            unset($_SESSION['sendData']);
        }
        $this->session->unset_userdata('municipality_id');
        $this->load->model('municipalities_model');
        $data['allMunicipalities']=$this->municipalities_model->getAllMunicipalities(1);
        $content['head'] = $this->load->view('head',null,true);
        $content['header'] = $this->load->view('header',null,true);
        $content['middleFront'] = $this->load->view('choose_municipality',$data,true);
        $content['footer'] = $this->load->view('footer',null,true);
        $this->load->view('index_front',$content);
    }

    function saveMunicipality(){
        if($_SERVER['REQUEST_METHOD']=='POST'){
            if(!$this->input->post('municipalities')){
                redirect(base_url().$this->lang->lang().'/front/chooseMunicipality', 'refresh');
            }
            $this->session->set_userdata('municipality_id', $this->input->post('municipalities'));
            redirect(base_url().$this->lang->lang().'/front/pickRepresentative', 'refresh');
        }else{
            if(!$this->session->userdata('municipality_id')){
                redirect(base_url().$this->lang->lang().'/front/chooseMunicipality', 'refresh');
            }
        }
    }

    function pickRepresentative(){
        if(isset($_SESSION['sendData'])){
            unset($_SESSION['sendData']);
        }
        $data['municipality']= $this->getCurrentMunicipalityModel();
        $this->load->model('representatives_model');
        $data['pratenici'] = $this->representatives_model->getAllPratenici($data['municipality'][0]->izborna_edinica_id);
        $data['sovetnici'] = $this->representatives_model->getAllSovetnici($data['municipality'][0]->municipality_id);
        $data['gradonacalnici'] = $this->representatives_model->getAllGradonacalnici($data['municipality'][0]->municipality_id);
//        var_dump($data);
//        die;

        $content['head'] = $this->load->view('head',null,true);
        $content['header'] = $this->load->view('header',null,true);
        $content['middleFront'] = $this->load->view('pick_representative',$data,true);
        $content['footer'] = $this->load->view('footer',null,true);
        $this->load->view('index_front',$content);
    }

    function writeMessage($functionality_id=false,$representative_id=false,$edit_message=false){
        if(!$this->session->userdata('municipality_id')){
            redirect(base_url().$this->lang->lang().'/front/chooseMunicipality', 'refresh');
        }
        if($functionality_id==false || $representative_id==false){
            redirect(base_url().$this->lang->lang().'/front/pickRepresentative', 'refresh');
        }
        
        $this->lang->load('form_validation');
        $this->load->library('form_validation');
        $rules = $this->getRules();
        $this->form_validation->set_rules($rules);
        $fields['required']="<b>%s</b> ".$this->lang->language['form_validation_field_required'];
        $fields['valid_email']="<b>%s</b> ".$this->lang->language['form_validation_valid_email'];
        $fields['numeric']="<b>%s</b> ".$this->lang->language['form_validation_numeric'];
        $this->form_validation->set_message($fields);
        
        $this->load->model('municipalities_model');
        $data['allMunicipalities']=$this->municipalities_model->getAllMunicipalities(1);



        $content['head'] = $this->load->view('head',null,true);
        $content['header'] = $this->load->view('header',null,true);

         if ($this->form_validation->run() == FALSE) {
             $data['sendData']['role_id']=$functionality_id;
             $data['sendData']['rep_id']=$representative_id;
             if(sizeof($this->form_validation->_field_data)!=0){
                 $data['sendData'] = $this->transformData($this->form_validation->_field_data);
                 var_dump($data['sendData']);
                 die;
             }
//             var_dump($this->form_validation->_field_data);
//             var_dump($_SESSION['sendData']);
             if($edit_message){
                 $data['sendData'] = $_SESSION['sendData'];
             }
             $content['middleFront'] = $this->load->view('write_message',$data,true);
        }
        else {
            $data['sendData'] = $_POST;
            $this->setSession($_POST);
            $content['middleFront'] = $this->load->view('preview_message',$data,true);
        }

        $content['footer'] = $this->load->view('footer',null,true);
        $this->load->view('index_front',$content);
    }

    function sendMessage(){
//        var_dump($_SESSION['sendData']);
//        die;
        if(isset($_SESSION['sendData'])){

            $this->load->model('representatives_model');
            $this->load->model('messages_model');
            $this->load->model('rep_message_model');
            $this->load->helper('uniqueid');

            $messageData = array(
                "message" => $_SESSION['sendData']["message"],
                "sender_name" => $_SESSION['sendData']["sender_name"],
                "sender_address" => $_SESSION['sendData']["sender_address"],
                "sender_city" => $_SESSION['sendData']["sender_city"],
                "municipality_id" => $_SESSION['sendData']["municipality_id"],
                "sender_email" => $_SESSION['sendData']["sender_email"],
                "sender_phone" => $_SESSION['sendData']["sender_phone"]
            );

            $message_id = $this->messages_model->insertMessage($messageData);
            $message_tokken =uniqueid($message_id);

            if($_SESSION['sendData']['rep_id']=="all") {
                echo "test";
                //Slucaj koga porakata se prakja na povekje lopovi
                $curMunicipality = $this->getCurrentMunicipalityModel();
                switch ($_SESSION['sendData']['role_id']) {
                    case "1":
                        $representatives = $this->representatives_model->getAllPratenici($curMunicipality[0]->izborna_edinica_id);
                        break;
                    case "2":
                        $representatives = $this->representatives_model->getAllSovetnici($curMunicipality[0]->municipality_id);
                        break;
                    case "3":
                        $representatives = $this->representatives_model->getAllGradonacalnici($curMunicipality[0]->municipality_id);
                        break;
                }
                var_dump(sizeof($representatives));
                if(sizeof($representatives)>0){
                    foreach ($representatives as $key=>$val) {
                        $rep_message_data = array(
                            "rep_id"=>$val->rep_id,
                            "message_id"=>$message_id,
                            "message_token"=>$message_tokken,
                            "message_status"=>0
                        );
                        $this->rep_message_model->insertRepMessage($rep_message_data);
                    }
                }
            
            }else {
                //Slucaj koga porakata se prakja na eden lopov
                $rep_message_data = array(
                    "rep_id"=>$_SESSION['sendData']['rep_id'],
                    "message_id"=>$message_id,
                    "message_token"=>$message_tokken,
                    "message_status"=>0
                );
                $this->rep_message_model->insertRepMessage($rep_message_data);
            }
            /*
             * Ako e seto ova uspesno vo toj slucaj treba da mu se prati mail na korisnikot
             * vo koj kje se generira link za potvrda na porakata(t.e validnosta na negoviot mail)
             * Od ovde treba da se redirectira na view na koe kje mu se kaze na korinikot deka mu stignalo mail.
             * Pred da se napravi redirect treba da se iscisti sesijata.
             */



        }
    }

    function qustionsAnswers($functionality_id=false,$representative_id=false){
        if(!$this->session->userdata('municipality_id')){
            redirect(base_url().$this->lang->lang().'/front/chooseMunicipality', 'refresh');
        }
        if($functionality_id==false || $representative_id==false){
            redirect(base_url().$this->lang->lang().'/front/pickRepresentative', 'refresh');
        }
        if($representative_id=="all"){
            //Ovde treba da se zemat prasanjata i dogovorite do/od site lopovi koi ja imaat konkretnata funkcija
        }else{
            //Zemi go lopovot so id $representative_id
        }

        $content['head'] = $this->load->view('head',null,true);
        $content['header'] = $this->load->view('header',null,true);
        $content['middleFront'] = $this->load->view('questions_answers',null,true);
        $content['footer'] = $this->load->view('footer',null,true);
        $this->load->view('index_front',$content);
        
    }

    function transformData($fieldArray){
        $tArray = array();
        foreach ($fieldArray as $key=>$val) {
            $tArray[$key]=$val['postdata'];
        }
        return $tArray;
    }

    function setSession($arr){
        unset($_SESSION['sendData']);
        $_SESSION['sendData'] = $arr;
    }

    function getCurrentMunicipalityModel(){
        $this->load->model('municipalities_model');
        $munModel = $this->municipalities_model->getMunicipalityById($this->session->userdata('municipality_id'));
        return $munModel;
    }

    function getRules(){
        $rules = array(
            array(
            'field'   => 'message',
            'label'   => 'lang:message',
            'rules'   => 'required|max_length[1000]'
            ),
            array(
            'field'   => 'date_created',
            'label'   => 'lang:date_created',
            'rules'   => ''
            ),
            array(
            'field'   => 'sender_name',
            'label'   => 'lang:sender_name',
            'rules'   => 'required'
            ),
            array(
            'field'   => 'sender_address',
            'label'   => 'lang:sender_address',
            'rules'   => 'required'
            ),
            array(
            'field'   => 'sender_city',
            'label'   => 'lang:sender_city',
            'rules'   => 'required'
            ),
            array(
            'field'   => 'municipality_id',
            'label'   => 'lang:municipality_id',
            'rules'   => 'required'
            ),
            array(
            'field'   => 'sender_email',
            'label'   => 'lang:sender_email',
            'rules'   => 'required|valid_email'
            ),
            array(
            'field'   => 'sender_confirm_email',
            'label'   => 'lang:sender_confirm_email',
            'rules'   => 'required|valid_email'
            ),
            array(
            'field'   => 'sender_phone',
            'label'   => 'lang:sender_phone',
            'rules'   => ''
            )
        );
        return $rules;
    }

    

}
